package samsung.sds.business.vdiManagementSystem.vdiManagement.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import samsung.sds.business.vdiManagementSystem.systemManagement.model.SystemInfoEntity;
import samsung.sds.business.vdiManagementSystem.vdiManagement.model.VDIInfoEntity;
import samsung.sds.business.vdiManagementSystem.vdiManagement.model.VDISystemREndity;
import samsung.sds.business.vdiManagementSystem.vdiManagement.model.VDIUserREntity;
import samsung.sds.business.vdiManagementSystem.vdiManagement.model.VdiHistoryEntity;
import samsung.sds.business.vdiManagementSystem.vdiManagement.service.VDIManagementService;
import samsung.sds.business.vdiManagementSystem.vdiManagement.service.VdiHistoryService;
import samsung.sds.departmentManagement.model.DepartmentEntity;
import samsung.sds.departmentManagement.service.DepartmentManagementService;
import samsung.sds.groupManagement.model.GroupUserEntity;
import samsung.sds.groupManagement.service.GroupUserManagementService;
import samsung.sds.system.common.baseQuery.model.PageData;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.utils.CommonTools;
import samsung.sds.system.utils.Constants;
import samsung.sds.userManagement.model.UserEntity;
import samsung.sds.userManagement.service.UserManagementService;

@Controller
@RequestMapping("/vdiManagement")
public class VDIManagementController {
	
	@Autowired
	private DepartmentManagementService departmentManagementServiceImpl;
	
	@Autowired
	private UserManagementService userManagementServiceImpl;
	
	@Autowired
	private VDIManagementService vdiManagementServiceImpl;
	
	@Autowired
	private VdiHistoryService vdiHistoryServiceImpl;
	
	@Autowired
	private GroupUserManagementService groupUserManagementServiceImpl;

	private final static String URL = "/business/vdiManagementSystem/vdiManagement/";

	/**
	 * 跳转至VDI详细信息Tab页面
	 * @param request
	 * @param modelMap
	 * @param vdiId
	 * @return
	 */
	@RequestMapping(value = "/toVDIInfoTab",method=RequestMethod.POST)
	public String toVDIInfoTab(ModelMap modelMap,	String vdiId) {
		if (vdiId != null && vdiId.length() > 0) {
			modelMap.addAttribute("vdiId", vdiId);
		}
		return URL + "vdiInfoTab";
	}

	@RequestMapping(value = "/vdiHistoryPageList_sitemesh_popup")
	public String vdiHistoryPageList(HttpServletRequest request,
			ModelMap modelMap, String vdiId) {
		if (vdiId != null && vdiId.length() > 0) {
			modelMap.addAttribute("vdiId", vdiId);
		}
		return URL + "vdiHistoryList";
	}

	/**
	 * 
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="/toAddVDIInfoTab_sitemesh_popup")
	public String toAddVDIInfoTab(HttpServletRequest request,ModelMap modelMap){
		String vdiId = "";
		if (request.getParameter("vdiId") != null && !"".equals(request.getParameter("vdiId"))) {//修改信息
			vdiId = request.getParameter("vdiId");
			
			VDIInfoEntity vdi = new VDIInfoEntity();
			vdi.setId(vdiId);
			VDIInfoEntity vdiInfoEntity = vdiManagementServiceImpl.queryVdiListById(vdi);
			
			List<SystemInfoEntity> listSys = vdiManagementServiceImpl.queryVdiSystemREndity(vdi);
			List<UserEntity> listUser = vdiManagementServiceImpl.queryVdiUserREndity(vdi);
			String systems= "" ,systemIds = "" , usernames= "" , cnusers = "";
			for(SystemInfoEntity systemInfoEntity : listSys){
				systems += systemInfoEntity.getName() + ",";
				systemIds += systemInfoEntity.getId() + ",";
			}
			
			for(UserEntity userEntity : listUser){
				usernames += userEntity.getUsername() + ",";
				cnusers += userEntity.getCn_name() + ",";
			}
			
			modelMap.addAttribute("vdiId", vdiId);
			modelMap.addAttribute("vdiBase", vdiInfoEntity);
			modelMap.addAttribute("systems", systems.length()==0?systems:systems.substring(0, systems.length()-1));
			modelMap.addAttribute("systemIds", systemIds.length()==0?systemIds:systemIds.substring(0, systemIds.length()-1));
			modelMap.addAttribute("usernames", usernames.length()==0?usernames:usernames.substring(0, usernames.length()-1));
			modelMap.addAttribute("cnusers", cnusers.length()==0?cnusers:cnusers.substring(0, cnusers.length()-1));
		}
		return URL+"addOrUpdateVDIInfoDetail";
	}
	
	/**
	 * 弹出用户查询窗口，跳转至添加用户窗口
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/addUserForGroup_sitemesh_popup",method=RequestMethod.GET)
	public String groupUserSelectPopup(ModelMap model){		
		return  URL+"addUserPopup";
	}
	
	@RequestMapping(value = "/addOrUpdateVDI")
	@ResponseBody
	public String addOrUpdateVdiInfo(HttpServletRequest request, String opertype,  VDIInfoEntity vdiInfo){
		String userNames[] = null ;
		
		String systemName = request.getParameter("systemName") == null ? "" : request.getParameter("systemName");
		String cnName = request.getParameter("cnName") == null ? "" : request.getParameter("cnName");
		
		if (request.getParameter("userName").length() != 0 && cnName.length() > 0) {
			userNames = request.getParameter("userName").split(","); //用户
		}
		String systems[] = null ;
		if (request.getParameter("system").length() != 0 && systemName.length() > 0) {
			systems = request.getParameter("system").split(","); //系统id
		}
		
		String userName = CommonTools.getSessionUserName();
		VdiHistoryEntity entity = new VdiHistoryEntity();
		String currentDateTime =CommonTools.getCurrentDateTime();
		
		entity.setNewUserName(userName);
		entity.setVdi_id(vdiInfo.getId());
		entity.setNewVdiTime(currentDateTime);
		entity.setId(CommonTools.getKeyUUID());
		
		if(!opertype.equals("modify")) {
			vdiInfo.setId(CommonTools.getKeyUUID());
			vdiInfo.setCreateUser(userName);
			int i = vdiManagementServiceImpl.insertVdiInfo(vdiInfo);
			entity.setVdi_id(vdiInfo.getId());
			insertData(userNames, systems, vdiInfo);
			
			entity.setContent(userName + "于" + currentDateTime + "创建了IP为：“" + vdiInfo.getIp() + "”的VDI。");
			vdiHistoryServiceImpl.insertHistoryEntity(entity);
			
			if(i >= 0)
				return Constants.SUCCESS_CODE + "," + vdiInfo.getId();
			else
				return Constants.FAILURE_CODE;
		}
		else {
			deleteData(systemName,cnName ,vdiInfo);
			insertData(userNames, systems, vdiInfo);
			
			try {
				String result = userName + "于" + CommonTools.getCurrentDateTime() + "做出修改: " + writeLog(vdiInfo);
				if (systemName.length() > 0) {
					result += "将“SYSTEM”修改为：" + systemName.substring(0,systemName.length() - 1) + "。";
				}
				if (cnName.length() > 0) {
					result += "将“USERNAME”修改为：" + cnName.substring(0,cnName.length() - 1) + "。";
				}
				entity.setContent(result);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			vdiInfo.setLastModifyUser(userName);
			int i = vdiManagementServiceImpl.updateVDIInfoDetail(vdiInfo);
			
			vdiHistoryServiceImpl.insertHistoryEntity(entity);
			if(i >= 0)
				return Constants.SUCCESS_CODE + "," + vdiInfo.getId();
			else
				return Constants.FAILURE_CODE;
		}
	}
	/**
	 * 写日志
	 * @param vdiInfoEntity
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	private String writeLog(VDIInfoEntity vdiInfoEntity) throws IllegalArgumentException, IllegalAccessException{
		String result = "";
		VDIInfoEntity old = vdiManagementServiceImpl.queryVdiListById(vdiInfoEntity);
		Field[] oldFields = old.getClass().getDeclaredFields();
		Field[] newFields = vdiInfoEntity.getClass().getDeclaredFields();
		
        for (int j = 0; j < newFields.length; j++) {
        	newFields[j].setAccessible(true);
        	oldFields[j].setAccessible(true);
        	String nString = "";
    		String oString = "";
        	if (null != newFields[j].get(vdiInfoEntity)) {
        		nString = newFields[j].get(vdiInfoEntity).toString();
			}
        	if (null != oldFields[j].get(old)) {
        		oString = oldFields[j].get(old).toString();
			}
        	
        	if (newFields[j].getName().equals("lastModifyUser") || newFields[j].getName().equals("createTime") 
        			|| newFields[j].getName().equals("LastModifyTime") || newFields[j].getName().equals("createUser")) {
			}else if (null != nString && !oString.equals(nString)) {
				if (newFields[j].getName().equals("department")) {
					List<DepartmentEntity> oldDepts = departmentManagementServiceImpl.queryDepartmentList(oString);
					List<DepartmentEntity> newDepts = departmentManagementServiceImpl.queryDepartmentList(nString);
					result += "将“" + newFields[j].getName() + "”的值： " + getDept(oldDepts,oString).getDeptName() + 
							"，改为：" + getDept(newDepts,nString).getDeptName() + "。 ";
				}else{
					result += "将“" + newFields[j].getName() + "”的值： " + oString + "，改为：" + nString + "。 ";
				}
        		
			}
        }
		return result;
	}
	/**
	 * 获取部门名称
	 * @param list
	 * @param id
	 * @return
	 */
	private DepartmentEntity getDept(List<DepartmentEntity> list, String id){
		DepartmentEntity departmentEntity = null;
		for(DepartmentEntity depart : list){
			if (depart.getDeptId().equals(id)) {
				departmentEntity = depart;
			}
		}
		return departmentEntity;
	}
	
	/**
	 * 插入关系数据
	 * @param userNames
	 * @param systems
	 * @param vdiInfoEntity
	 */
	private void insertData(String userNames[],String systems[],VDIInfoEntity vdiInfoEntity){
		String user = CommonTools.getSessionUserName();
		VDIUserREntity vdiUserREntity = null;
		VDISystemREndity vdiSystemREndity = null;
		if (userNames != null) {
			for(String userName : userNames){
				vdiUserREntity = new VDIUserREntity();
				vdiUserREntity.setId(CommonTools.getKeyUUID());
				vdiUserREntity.setVdiId(vdiInfoEntity.getId());
				vdiUserREntity.setUserName(userName);
				vdiUserREntity.setCreateUser(user);
				vdiManagementServiceImpl.insertVdiUserR(vdiUserREntity);
			}
		}
		
		if (systems != null) {
			for(String system : systems){
				vdiSystemREndity = new VDISystemREndity();
				vdiSystemREndity.setId(CommonTools.getKeyUUID());
				vdiSystemREndity.setVdiId(vdiInfoEntity.getId());
				vdiSystemREndity.setSystemId(system);
				vdiSystemREndity.setCreateUser(user);
				vdiManagementServiceImpl.insertVdiSystemR(vdiSystemREndity);
			}
		}
	}
	
	/**
	 * 删除关系数据
	 * @param userNames
	 * @param systems
	 * @param vdiInfoEntity
	 */
	private void deleteData(String systemName,String cnName,VDIInfoEntity vdiInfoEntity){
		if (systemName != null && systemName.length() > 0) {
			VDISystemREndity vdiSystemREndity = new VDISystemREndity();
			vdiSystemREndity.setVdiId(vdiInfoEntity.getId());
			vdiManagementServiceImpl.deleteVdiSystemR(vdiSystemREndity);
		}
		
		if (cnName != null && cnName.length() > 0) {
			VDIUserREntity vdiUserREntity = new VDIUserREntity();
			vdiUserREntity.setVdiId(vdiInfoEntity.getId());
			vdiManagementServiceImpl.deleteVdiUserR(vdiUserREntity);
		}
	}
	
	/**
	 * 查出所有部门
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryDepts", method = RequestMethod.POST)
	@ResponseBody
	public List<DepartmentEntity> queryDepartment() {
		QueryParam param = new QueryParam();
		return departmentManagementServiceImpl.queryList(param);

	}
	
	/**
	 * 查找所有用户（调用用户表分页接口）
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/queryUsersNotInGroup",method=RequestMethod.POST)
	@ResponseBody
	public PageData<GroupUserEntity> queryUsersNotInGroup(HttpServletRequest request){
		
		QueryParam param = CommonTools.getQueryParam(request);
		return groupUserManagementServiceImpl.queryNoGroupUsersListPage(param );
	} 
	
	@RequestMapping(value = "/checkVdiIP")
	@ResponseBody
	public Map<String, Boolean> checkVdiIPExist(HttpServletRequest request, String ip) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		VDIInfoEntity vdiInfo = new VDIInfoEntity();
		vdiInfo.setIp(ip);
		VDIInfoEntity vdiInfoEntity = vdiManagementServiceImpl.queryVdiListByIp(vdiInfo);
		if(vdiInfoEntity == null) {
			map.put("result", true);
		}
		else {
			map.put("result", false);
		}
		return map;
	}
	
	@RequestMapping(value = "/checkLoginName")
	@ResponseBody
	public Map<String, Boolean> checkLoginNameExist(HttpServletRequest request, String loginName) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		VDIInfoEntity vdiInfo = new VDIInfoEntity();
		vdiInfo.setLoginName(loginName);
		List<VDIInfoEntity> vdiInfos = vdiManagementServiceImpl.queryByLoginName(vdiInfo);
		if(null == vdiInfos || vdiInfos.size() == 0) {
			map.put("result", true);
		}
		else {
			map.put("result", false);
		}
		return map;
	}
	/**
	 * VDI信息管理List
	 */
	@RequestMapping(value="/vdiInfoList")
	public String departmentList(){		
		return URL+"vdiInfoManagement";
	}
	
	/**
	 * search vdi history by vdiid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/vdiHistoryList")
	@ResponseBody
	public PageData<VdiHistoryEntity> vdiHistoryList(HttpServletRequest request) {
		QueryParam param = CommonTools.getQueryParam(request);
		String vdiId = (String) param.getQueryCondition().get("vdiId");
		PageData<VdiHistoryEntity> pageData = new PageData<VdiHistoryEntity>();
		if (vdiId != null && vdiId.length() > 0) 
		{
			List<VdiHistoryEntity> list = vdiHistoryServiceImpl
					.queryListPageByIdAndContent(param);
			pageData.setQueryResult(list);
			pageData.setQueryParam(param);
		}
		return pageData;
	}

	
	/**
	 * 查询部门
	 */
	@RequestMapping(value="/queryDepartments",method = RequestMethod.POST)
	@ResponseBody
	public List<DepartmentEntity> queryDepartments() {	
		List<DepartmentEntity> departmentEntitys = new ArrayList<DepartmentEntity>();
		QueryParam param = new QueryParam();
		departmentEntitys = departmentManagementServiceImpl.queryList(param);
		return departmentEntitys;
	}
	
	
	/**
	 * 根据查询条件查询vdiinfo
	 */
	@RequestMapping(value="/queryVdiInfos",method = RequestMethod.POST)
	@ResponseBody
	public PageData<VDIInfoEntity> queryVdiInfos(HttpServletRequest request) {	
		QueryParam param = CommonTools.getQueryParam(request);
		return vdiManagementServiceImpl.queryVdiInfoQueryListPage(param);
	}
	

	
	/**
	 * 删除vdi
	 * @param request
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/removeVdiFromDepartment",method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String removeVdiFromDepartment(HttpServletRequest request) throws UnsupportedEncodingException {
		
		String deptId = new String( "-1" );
		String idStr = request.getParameter("ids");
		String temUserName = URLDecoder.decode(idStr, "UTF-8");
		String[] ids = temUserName.split(",");
		List<String> list = new ArrayList<String>();

	    list = Arrays.asList(ids);
		
		int removeCount = vdiManagementServiceImpl.updateVDIInfo(list);
		int removeVdiUserCount = vdiManagementServiceImpl.deleteVdiUser(list);
		int removeVdiSysCount = vdiManagementServiceImpl.deleteVdiSys(list);

		
		if( removeCount > 0 ){
			return Constants.SUCCESS_CODE;
		}else{
			return Constants.FAILURE_CODE;
		}
	}

	
	/**
	 * 点击部门查询部门下面的vdi信息
	 * @param request
	 */
	@RequestMapping(value="/queryVdiInfosInDepartment",method = RequestMethod.POST)
	@ResponseBody
	public PageData<VDIInfoEntity> queryUsersInDepartment(HttpServletRequest request){
		QueryParam param = CommonTools.getQueryParam(request);
		return vdiManagementServiceImpl.vdiInfoQueryListPage(param);
	}
	
	/**
	 *部门校验
	 * @throws IOException
	 */
	@RequestMapping(value="/departmentValidate",method = RequestMethod.POST)
	@ResponseBody
	public boolean departmentValidate(DepartmentEntity tmpDepartmentEntity) throws IOException{
		
		boolean validateResult = true;
		
		DepartmentEntity departmentEntity = departmentManagementServiceImpl.findUniqueByProperty( tmpDepartmentEntity );
		if( null != departmentEntity ){
			
			validateResult = false;
		}
		return validateResult;
	}
	/**
	 * search vdi history list
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/searchVdiHistoryList")
	@ResponseBody
	public PageData<VdiHistoryEntity> searchVdiHistoryList(
			HttpServletRequest request) {
		QueryParam param = CommonTools.getQueryParam(request);
		String vdiId = (String) param.getQueryCondition().get("vdiId");
		PageData<VdiHistoryEntity> pageData = new PageData<VdiHistoryEntity>();
		if (vdiId != null && vdiId.length() > 0) 
		{
			List<VdiHistoryEntity> list = vdiHistoryServiceImpl
					.queryListPageByIdAndContent(param);
			pageData.setQueryResult(list);
			pageData.setQueryParam(param);
		}
		return pageData;
	}
}
